package cn.hzc.fortess.system.service;

import cn.hzc.fortess.core.common.annotion.CURDLog;
import cn.hzc.fortess.core.common.annotion.CURDType;
import cn.hzc.fortess.core.shiro.ShiroKit;
import cn.hzc.fortess.system.dao.SettingDao;
import cn.hzc.fortess.system.entity.SettingBean;
import cn.hzc.fortess.system.page.Pagination;
import cn.hzc.fortess.system.search.SettingSearch;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    SettingDao settingDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CURDLog(value = "新增配置")
    public void add(SettingBean entity) {
        entity.setCreateTime(new Date());
        entity.setCreateUser(ShiroKit.getUser().getAccount());
        settingDao.insert(entity);
    }

    @Override
    @CURDLog(value = "更新配置", curdType = CURDType.EDIT)
    public void update(SettingBean entity) {
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(ShiroKit.getUser().getAccount());
        settingDao.update(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CURDLog(value = "删除配置", curdType = CURDType.DELETE)
    public void delete(Integer id) {
        settingDao.delete(id);
    }


    @Override
    public SettingBean getById(Integer id) {
        return settingDao.find(id);
    }


    @Override
    public Pagination getPage(SettingSearch search) {

        Pagination pagination = new Pagination();
        pagination.setCount(settingDao.count(search));
        if (pagination.getCount() > 0) {
            pagination.setData(settingDao.page(search));
        }
        return pagination;
    }

    @Override
    public String getValByKey(String key) {
        return settingDao.findValByKey(key);
    }

    @Override
    public String getValByKey(String key, String defVal) {
        String val =  settingDao.findValByKey(key);
        if(StringUtils.isBlank(val)){
            return defVal;
        }
        return val;
    }

    @Override
    public SettingBean getByKey(String key) {
        return settingDao.findByKey(key);
    }
}
